import { Directive, ElementRef, Input, HostListener, Output, EventEmitter } from '@angular/core';

type SortBy = '' | 'desc' | 'asc';

@Directive({
	selector: '[mDataTableSort]',
})
export class DataTableSortDirective {
	_sortBy: SortBy;
	@Input('mDataTableSort')
	get sort(): SortBy {
		return this._sortBy;
	}
	set sort(by: SortBy) {
		this._sortBy = by;
		this.setSortClass();
	}

	@Output()
	sortChange = new EventEmitter<string>();

	constructor(private el: ElementRef<HTMLTableColElement>) {}

	@HostListener('click') click() {
		const sort = this.sort === 'asc' ? 'desc' : 'asc';
		this.sortChange.next(sort);
	}

	setSortClass() {
		const cList = this.el.nativeElement.classList;
		// init
		cList.add('data-sorting');
		cList.remove('data_desc');
		cList.remove('data_asc');

		// sort
		if (this.sort === 'asc') {
			cList.add('data_asc');
		} else if (this.sort === 'desc') {
			cList.add('data_desc');
		}
	}
}
